import React             from 'react';
import PageTitle         from 'component/page-title/index.jsx';
import Product           from 'service/product-service.jsx';
import MUtil             from 'util/mm.jsx';
import CategorySelector  from './category-selector.jsx';
import FileUploader      from 'util/file-uploader/index.jsx';
import RichEditor        from 'util/rich-editor/index.jsx';
import './save.scss';
const _product = new Product();
const _mm   = new MUtil();

class ProductSave extends React.Component{
     constructor(props){
     	super(props);
     	this.state = {
            id               : this.props.match.params.pid,
            subtitle         : '',
            detail           : '',
            name             : '',
     		categoryId       : 0,
     		parentCategoryId : 0,
            subImages        : [],
            price            : '',
            stock            : '',
            status           : 1//状态为1为在售状态
     	}
     }
     componentDidMount(){
        this.loadProuct();
     }
     loadProuct(){
        //id存在表示编辑功能需要表单回填
        if(this.state.id){
            _product.getProduct(this.state.id).then(res => {
                let images = res.subImages.split(',');
                res.subImages = images.map((imgUri) => {
                    return {
                        uri : imgUri,
                        url : res.imageHost + imgUri
                    }
                });
                res.defaultDetail = res.detail;
                this.setState(res);
            },errMsg => {
                _mm.errorTips(errMsg);
            });
        }
     }
     //简单字段的处理例如商品描述，商品名称,商品价格，商品库存
     onValueChange(e){
          let name = e.target.name,
              value = e.target.value;
          this.setState({
            [name] : value
          });
     }
     onCategoryChange(categoryId,parentCategoryId){
        this.setState({
            categoryId       : categoryId,
            parentCategoryId : parentCategoryId
        });
     }
     //上传图片成功
     onUploadSuccess(res){
        let subImages = this.state.subImages;
        subImages.push(res);
        this.setState({
            subImages : subImages
        });
    }
     //上传图片失败
     onUploadError(errMsg){
        _mm.errorTips(errMsg);
     }
     //图片删除
     onImageDelete(e){
         let index = parseInt(e.target.getAttribute('index')),
             subImages = this.state.subImages;
             console.log(index);
             console.log(subImages);
         subImages.splice(index,1);
         this.setState({
            subImages : subImages
         });
     }
     onDetailValueChange(value){
           this.setState({
            detail : value
           });
     }
     //将subImages从数组转化为字符串
     getSubImagesString(){
        return this.state.subImages.map((img) => img.uri).join(',');
     }
     //提交表单
     onSubmit(){
        let product = {
            subtitle         : this.state.subtitle,
            detail           : this.state.detail,
            name             : this.state.name,
            categoryId       : this.state.categoryId,
            parentCategoryId : this.state.parentCategoryId,
            subImages        : this.getSubImagesString(),
            price            : parseFloat(this.state.price),
            stock            : parseInt(this.state.stock),
            status           : this.state.status
        },
         productCheckResult = _product.checkProduct(product);
        if(this.state.id){
            product.id = this.state.id;
        }
        // 表单验证成功
        if(productCheckResult.status){
            _product.saveProduct(product).then((res) => {
                _mm.successTips(res);
                this.props.history.push('/product/index');
            }, (errMsg) => {
                _mm.errorTips(errMsg);
            });
        }
        // 表单验证失败
        else{
            _mm.errorTips(productCheckResult.msg);
        }
        
    }
     render(){
        return (
           <div id="page-wrapper">
                <PageTitle title={this.state.id ? '编辑商品' : '添加商品'}/>
                <div className="form-horizontal">
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品名称</label>
                        <div className="col-sm-5">
                            <input type="text" className="form-control" placeholder="请输入商品名称"
                            name = "name" value={this.state.name}
                            onChange={(e) => {this.onValueChange(e)}}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品描述</label>
                        <div className="col-md-5">
                            <input type="text" className="form-control" placeholder="请输入商品描述" 
                            name = "subitle" value={this.state.subtitle}
                            onChange={(e) => {this.onValueChange(e)}}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">所属分类</label>
                        <CategorySelector categoryId={this.state.categoryId} parentCategoryId={this.state.parentCategoryId} onCategoryChange={(categoryId,parentCategoryId) => {this.onCategoryChange(categoryId,parentCategoryId)}}/>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品价格</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control" placeholder="价格"
                                name = "price"  value={this.state.price}
                                onChange={(e) => {this.onValueChange(e)}} />
                                <span className="input-group-addon">元</span>
                            </div> 
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品库存</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="text" className="form-control" placeholder="库存"
                                name = "stock" value={this.state.stock}
                                onChange={(e) => {this.onValueChange(e)}} />
                                <span className="input-group-addon">件</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品图片</label>
                        <div className="col-md-10">
                            { this.state.subImages.length > 0 ? this.state.subImages.map((image,index) => 
                                (<div key={index} className="img-con"><img className="img" src={image.url} />
                                    <i className="fa fa-close" index={index} onClick={(e) => {this.onImageDelete(e)}}></i></div>))
                                : (<div>请上传图片</div>)}
                        </div>
                        <div className="col-md-offset-2 col-md-10 qi">
                            <FileUploader  onSuccess={(res) => {this.onUploadSuccess(res)}}
                             onError={(errMsg) => {this.onUploadError(errMsg)}}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品详情</label>
                        <div className="col-md-10">
                           <RichEditor detail={this.state.detail} defaultDetail={this.state.defaultDetail}onValueChange={(value) => {this.onDetailValueChange(value)}}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-sm-offset-2 col-sm-10">
                            <button type="submit" className="btn btn-primary"
                            onClick={(e) => {this.onSubmit(e)}}>提交</button>
                        </div>
                    </div>
                </div>
           </div>
         );
     }
}


export default ProductSave;
